package com.danskin.wechat.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.dto.MessageAnalyzeDto;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.WxMsgReplyDetailService;
import com.danskin.wechat.util.BeanUtil;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.vo.WxMsgReplyDetailVo;

@Controller
@RequestMapping("messageAnalyze")
public class MessageAnalyzeController extends BaseController {

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Autowired
	private WxMsgReplyDetailService wxMsgReplyDetailService;

	/**
	 * 跳转到消息分析报表页面
	 * 
	 * @param model
	 * @return
	 * @author makunsmac
	 */
	@RequestMapping(value = "jumpMessageAnalyze", method = RequestMethod.GET)
	public String jumpMessageAnalyze(Model model) {

		// 获取mpId
		Integer mpId = getMpId();
		// 获取微信公众号access_token
		String accessToken = getMPWithAccessToken(mpId);

		// 分时数据结束时间
		String endDateHour = new SimpleDateFormat("yyyy-MM-dd")
				.format(com.danskin.wechat.util.DateUtils.getBeforeDay(-1));

		// 昨天数据结束时间
		String endDateDay = new SimpleDateFormat("yyyy-MM-dd")
				.format(com.danskin.wechat.util.DateUtils.getBeforeDay(-8));

		// 周报开始时间
		Integer startDateWeek = -7;
		// 周报结束时间
		Integer endDateWeek = -1;

		// 月报开始时间
		Integer beginDateMonth = -30;
		// 月报结束时间
		Integer endDateMonth = -1;

		// 消息分时数据列表
		List<MessageAnalyzeDto> messageSendHourList = new ArrayList<MessageAnalyzeDto>();
		List<MessageAnalyzeDto> messageSendHourListTemp = new ArrayList<MessageAnalyzeDto>();

		// 消息昨天数据列表
		List<MessageAnalyzeDto> messageSendDayList = new ArrayList<MessageAnalyzeDto>();
		List<MessageAnalyzeDto> messageSendDayListTemp = new ArrayList<MessageAnalyzeDto>();

		// 消息周数据列表
		List<MessageAnalyzeDto> messageSendWeekList = new ArrayList<MessageAnalyzeDto>();
		List<MessageAnalyzeDto> messageSendWeekListTemp = new ArrayList<MessageAnalyzeDto>();

		// 消息月数据列表
		List<MessageAnalyzeDto> messageSendMonthList = new ArrayList<MessageAnalyzeDto>();
		List<MessageAnalyzeDto> messageSendMonthListTemp = new ArrayList<MessageAnalyzeDto>();

		try {
			// 获取消息分时数据
			String messageSendHourString = WeiXinOpenApiClient.createInstance().getMsgHourCount(accessToken,
					endDateHour, endDateHour);
			com.alibaba.fastjson.JSONObject messageSendHourJSON = JSON.parseObject(messageSendHourString);
			if (messageSendHourJSON.containsKey("list")) {
				messageSendHourListTemp = JSON.parseArray(messageSendHourJSON.getString("list"),
						MessageAnalyzeDto.class);
			}

			// 获取消息昨天数据
			String messageSendDayString = WeiXinOpenApiClient.createInstance().getMsgWeekCount(accessToken, endDateDay,
					endDateDay);
			com.alibaba.fastjson.JSONObject messageSendDayJSON = JSON.parseObject(messageSendDayString);
			if (messageSendDayJSON.containsKey("list")) {
				messageSendDayListTemp = JSON.parseArray(messageSendDayJSON.getString("list"), MessageAnalyzeDto.class);
			}
			// 获取消息周数据
			for (int i = 0; i < 180; i++) {
				if (i % 7 == 0) {
					String messageSendWeekString = WeiXinOpenApiClient.createInstance().getMsgWeekCount(accessToken,
							sdf.format(com.danskin.wechat.util.DateUtils.getBeforeDay(startDateWeek - i)),
							sdf.format(com.danskin.wechat.util.DateUtils.getBeforeDay(endDateWeek - i)));
					com.alibaba.fastjson.JSONObject messageSendWeekJSON = JSON.parseObject(messageSendWeekString);
					if (messageSendWeekJSON.containsKey("list")) {
						messageSendWeekListTemp.addAll(
								JSON.parseArray(messageSendWeekJSON.getString("list"), MessageAnalyzeDto.class));
					}
				}
			}

			// 获取消息月数据
			for (int i = 0; i < 330; i++) {
				if (i % 30 == 0) {
					String messageSendMonthString = WeiXinOpenApiClient.createInstance().getMsgMonthCount(accessToken,
							sdf.format(com.danskin.wechat.util.DateUtils.getBeforeDay(beginDateMonth - i)),
							sdf.format(com.danskin.wechat.util.DateUtils.getBeforeDay(endDateMonth - i)));
					com.alibaba.fastjson.JSONObject messageSendMonthJSON = JSON.parseObject(messageSendMonthString);
					if (messageSendMonthJSON.containsKey("list")) {
						messageSendMonthListTemp.addAll(
								JSON.parseArray(messageSendMonthJSON.getString("list"), MessageAnalyzeDto.class));
					}
				}
			}

			// 处理分时消息数据(把相同小时数的数据合并为一条数据)
			for (MessageAnalyzeDto temp : messageSendHourListTemp) {
				boolean state = false;
				for (MessageAnalyzeDto temp1 : messageSendHourList) {
					if (temp1.getRef_hour() == temp.getRef_hour()) {

						int msgUser = temp1.getMsg_user();
						msgUser += temp.getMsg_user();
						temp1.setMsg_user(msgUser);

						int msgCount = temp1.getMsg_count();
						msgCount += temp.getMsg_count();
						temp1.setMsg_count(msgCount);
						state = true;
					}
				}
				if (!state) {
					messageSendHourList.add(temp);
				}
			}

			// 处理昨天消息数据(把相同时间的数据合并为一条数据)
			for (MessageAnalyzeDto temp : messageSendDayListTemp) {
				boolean state = false;
				for (MessageAnalyzeDto temp1 : messageSendDayList) {
					if (temp1.getRef_date().equals(temp.getRef_date())) {

						int msgUser = temp1.getMsg_user();
						msgUser += temp.getMsg_user();
						temp1.setMsg_user(msgUser);

						int msgCount = temp1.getMsg_count();
						msgCount += temp.getMsg_count();
						temp1.setMsg_count(msgCount);
						state = true;
					}
				}
				if (!state) {
					messageSendDayList.add(temp);
				}
			}

			// 处理周消息数据(把相同时间的数据合并为一条数据)
			for (MessageAnalyzeDto temp : messageSendWeekListTemp) {
				boolean state = false;
				for (MessageAnalyzeDto temp1 : messageSendWeekList) {
					if (temp1.getRef_date().equals(temp.getRef_date())) {

						int msgUser = temp1.getMsg_user();
						msgUser += temp.getMsg_user();
						temp1.setMsg_user(msgUser);

						int msgCount = temp1.getMsg_count();
						msgCount += temp.getMsg_count();
						temp1.setMsg_count(msgCount);
						state = true;
					}
				}
				if (!state) {
					messageSendWeekList.add(temp);
				}
			}

			// 处理月消息数据(把相同时间的数据合并为一条数据)
			for (MessageAnalyzeDto temp : messageSendMonthListTemp) {
				boolean state = false;
				for (MessageAnalyzeDto temp1 : messageSendMonthList) {
					if (temp1.getRef_date().equals(temp.getRef_date())) {

						int msgUser = temp1.getMsg_user();
						msgUser += temp.getMsg_user();
						temp1.setMsg_user(msgUser);

						int msgCount = temp1.getMsg_count();
						msgCount += temp.getMsg_count();
						temp1.setMsg_count(msgCount);
						state = true;
					}
				}
				if (!state) {
					messageSendMonthList.add(temp);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BeanUtil.ListSort(messageSendWeekList);
		BeanUtil.ListSort(messageSendMonthList);

		model.addAttribute("messageSendHourList", messageSendHourList);
		model.addAttribute("messageSendDayList", messageSendDayList);
		model.addAttribute("messageSendWeekList", messageSendWeekList);
		model.addAttribute("messageSendMonthList", messageSendMonthList);

		return "reportStatistics/message_analyze";
	}

	/**
	 * 消息分析关键字分页查询
	 * 
	 * @param page
	 * @param request
	 * @return
	 * @author makunsmac
	 */
	@ResponseBody
	@RequestMapping(value = "getMsgSendVoList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getMsgSendVoList(Page page) {
		List<WxMsgReplyDetailVo> replyDetailList = new ArrayList<WxMsgReplyDetailVo>();

		try {
			Map map = getRequestParameter(getRequest());
			LoginUser loginUser = getLoginUser();
			map.put("mpId", loginUser.getMpId());
			page.setMap(map);

			replyDetailList = wxMsgReplyDetailService.listPageMsgReplyDetailList(page);
		} catch (Exception e) {
			LogUtil.error("======消息分析关键字分页查询异常", e);
		}
		return pagelistToJSONForBootStrapTable(replyDetailList, page);
	}
}
